package com.zxf.appliction.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zxf.appliction.domain.Params;
import com.zxf.appliction.domain.Users;
import com.zxf.appliction.service.UserService;

@RequestMapping("/user")
@Controller
public class UserController {

	@Autowired
	private UserService userService;

	private static Logger logger = Logger.getLogger(IndexsController.class);

	
	/**
	 * 添加新用户
	 * @param user
	 * @param username
	 * @param loginame
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/save")
	public @ResponseBody Map<String, Object> saveOrUpdate(Users user, String username, String loginame,
			HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> responseMap = new HashMap<String, Object>();

		Map<String, Object> param = new HashMap<String, Object>();
		if (null != user.getUserid()) {
			userService.updateUser(user);

		} else {
			userService.insertUser(user, param);

		}

		responseMap.put("method", "Create");
		responseMap.put("success", "true");
		responseMap.put("info", "新增成功！");
		return responseMap;
	}

	
	/**
	 * 用户列表
	 * @param params
	 * @param page
	 * @param limit
	 * @param start
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/userlist")
	public @ResponseBody JSONObject userlist(Params params, String page, String limit, String start,
			HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		// StringBuffer toJson=new StringBuffer();//用来放json数据
		JSONArray js = new JSONArray();
		// 页码
		int pageno = 1;
		if (null != page && !"".equals(page)) {
			pageno = Integer.parseInt(page);
		}
		pageno = params.getPage();
		// 每页数量
		int pageSize2 = Integer.parseInt(limit);
		int start2 = (pageno - 1) * pageSize2;
		
		List userlist2 = userService.getUserList3(start2, pageSize2);
		int totle = userService.getusertotle();
		
		obj.put("data", js.fromObject(userlist2));
		obj.put("total", totle); // 统计数量，这里写死10条
		obj.put("success", true);

	
		// json格式化后输出
		logger.info("userlist:"+ obj.toString());
		return obj;

	}

	
	/**
	 * 用户登录
	 * @param users
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/userlogin")
	public @ResponseBody JSONObject userlogin(Users users, HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		HttpSession session = request.getSession();
		// StringBuffer toJson=new StringBuffer();//用来放json数据
		// shiro验证
		/*
		 * Subject subject = SecurityUtils.getSubject(); // 已登陆则 跳到首页
		 * 
		 * UsernamePasswordToken token = new UsernamePasswordToken(
		 * users.getUserid().toString(), users.getPassword());
		 * token.setRememberMe(true); subject.login(token);
		 * 
		 * 
		 * if (subject.isAuthenticated()) { session.setAttribute("userinfo",
		 * users); //return "redirect:/"; }
		 */
		Users users2;
		// 得到生成的验证码
		String strCode = (String) session.getAttribute("randomCode");
		logger.info("UserAction>randomCode:" + strCode);
		// 定义一个msg变量，可用于存放错误信息，然后传到前台
		// 用于告诉前台时候登录成功
		boolean successe = false;
		if (!users.getCheckCode().toLowerCase().equals(strCode.toLowerCase())) {
			obj.put("success", false);
			obj.put("message", "验证码错误！");
			return obj;

		}

		users2 = userService.selectusers(users);

		if (null != users2) {
			users2.setPassword("");
			obj.put("users", users2);
			obj.put("success", true);
			session.setAttribute("userInfo", users2);
		} else {
			obj.put("success", false);
			obj.put("message", "用户名或者密码错误！");

		}

		// json格式化后输出
		logger.info("users:" + obj.toString());
		return obj;

	}

	
	/**
	 * 用户登录
	 * @param username
	 * @param password
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/buserlogin")
	public @ResponseBody JSONObject buserlogin(String username, String password, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		HttpSession session = request.getSession();
		// StringBuffer toJson=new StringBuffer();//用来放json数据
		Users users = new Users();
		Users users2;
		users.setUsername(username);
		users.setPassword(password);
		// 得到生成的验证码
		String strCode = (String) session.getAttribute("randomCode");
		logger.info("UserAction>randomCode:" + strCode);
		// 定义一个msg变量，可用于存放错误信息，然后传到前台
		// 用于告诉前台时候登录成功
		boolean successe = false;

		users2 = userService.selectusers(users);

		if (null != users2) {
			obj.put("users", users2);
			obj.put("success", true);
			session.setAttribute("userInfo", users2);

		} else {
			obj.put("success", false);
			obj.put("message", "用户名或者密码错误！");

		}

		// json格式化后输出
		logger.info(obj.toString());
		return obj;

	}

	/**
	 * 删除用户
	 * 
	 * @param user
	 * @param ids
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/deleUser")
	public @ResponseBody Map<String, Object> deleUser(Users user, String ids, HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> responseMap = new HashMap<String, Object>();

		String[] id = ids.split(",");
		for (int i = 0; i < id.length; i++) {
			userService.deleUser(Integer.parseInt(id[i]));

		}

		responseMap.put("method", "Create");
		responseMap.put("success", "true");
		responseMap.put("info", "新增成功！");
		return responseMap;
	}

	/**
	 * 取的session中的值
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getSessionUser")
	public @ResponseBody JSONObject getSessionUser(HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		HttpSession session = request.getSession();
		Users user;

		user = (Users) session.getAttribute("userInfo");
		if (null != user) {
			obj.put("user", user);
			obj.put("success", true);

		} else {
			obj.put("success", false);

		}
		return obj;
	}

}
